<template>
  <div>
    <el-card shadow="never" class="margin-30">
      <div slot="header">
        <el-button type="primary" size="mini" @click="openModal('')">新增角色</el-button>
      </div>
      <el-table :data="roleList" border stripe>
        <el-table-column
          type="index"
          label="#"
        />
        <el-table-column
          prop="roleName"
          label="角色名字"
        />
        <el-table-column
          prop="roleCode"
          label="角色编码"
        />
        <el-table-column
          prop="remark"
          label="备注"
        />
        <el-table-column
          prop="createTime"
          label="添加时间"
        />
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-button type="success" size="mini" @click="openModal(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        align="right"
        style="margin-top:20px;"
        :current-page="pagination.start"
        :page-sizes="pagination.sizes"
        :page-size="pagination.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      title="编辑角色"
      :visible.sync="roleVisible"
      width="30%"
      @close="closeModal"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="角色名称" size="small" prop="roleName">
              <el-input v-model="form.roleName" placeholder="角色名称" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="角色编码" size="small">
              <el-input v-model="form.roleCode" placeholder="角色编码" size="small" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="角色描述" size="small">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="2"
                placeholder="角色描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="选择菜单" size="small">
              <el-row :gutter="20">
                <el-col :span="6" :offset="0">
                  <el-checkbox v-model="form.expandAll" class="checkbox" @change="changeExpanded">展开/关闭</el-checkbox>
                </el-col>
                <el-col :span="6" :offset="1">
                  <el-checkbox v-model="form.selectedAll" class="checkbox" @change="changeSelect">全选/取消全选</el-checkbox>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="24" :offset="0">
                  <el-tree
                    ref="tree"
                    :data="menuList"
                    show-checkbox
                    node-key="id"
                    :props="defaultProps"
                  />
                </el-col>
              </el-row>

            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <span slot="footer">
        <el-button @click="roleVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  findRolesByPage as findRolesByPageApi,
  removeRole as removeRoleAPi,
  findRolePermissions as findRolePermissionsApi,
  findAllPermissions as findAllPermissionsApi,
  saveRolePermissions as saveRolePermissionsApi,
  updateRolePermissions as updateRolePermissionsApi
} from '@/api/auth/role'
import mix from '@/mixin'
export default {
  name: 'Role',
  mixins: [mix],
  data() {
    return {
      roleList: [],
      roleVisible: false,
      id: '',
      form: {
        expandAll: false,
        selectedAll: false
      },
      rules: {
        roleName: [{ required: true, trigger: 'blur', message: '请输入角色名称' }]
      },
      menuList: [],
      defaultProps: {
        label: 'title',
        children: 'children'
      }

    }
  },
  created() {
    this.getRolesList()
    this.getMenu()
  },
  methods: {
    // 改变全选展开
    changeExpanded(e) {
      const tree = this.$refs.tree
      const treeMap = tree.store.nodesMap
      for (var key in treeMap) {
        const item = treeMap[key]
        item.expanded = e
      }
    },
    // 改变全选选项
    changeSelect(e) {
      const tree = this.$refs.tree
      const treeMap = tree.store.nodesMap
      var selectedArray = []
      if (e) {
        for (var key in treeMap) {
          selectedArray.push(treeMap[key].data.id)
        }
      }
      tree.setCheckedKeys(selectedArray)
    },
    // 查询菜单
    getMenu() {
      findAllPermissionsApi()
        .then(res => {
          const { message, success, data } = res
          if (success) {
            this.menuList = data.menus
          } else {
            this.$message.error(message)
          }
        })
    },
    // 获取角色详情
    getRoleDetail() {
      findRolePermissionsApi(this.id)
        .then(res => {
          const { data, message, success } = res
          if (success) {
            console.log(data)
            this.form = data.role
            this.$refs.tree.setCheckedKeys(data.role.permissionIds)
          } else {
            this.$message.error(message)
          }
        })
    },
    // 打开弹框
    openModal(id) {
      this.roleVisible = true
      this.id = id
      if (id) {
        this.getRoleDetail()
      }
    },
    // 保存
    save() {
      this.$refs.form.validate((valid, error) => {
        if (valid) { // 验证成功
          var api = null
          var mes = ''
          delete this.form.selectedAll
          delete this.form.expandAll
          if (this.id) { // 修改角色
            api = updateRolePermissionsApi
            mes = '修改'
          } else { // 增加角色
            api = saveRolePermissionsApi
            mes = '新增'
          }
          this.form.permissionIds = this.$refs.tree.getCheckedKeys()

          api(this.form)
            .then(res => {
              const { message, success } = res
              if (success) {
                this.$message.success(mes + '角色成功!')
                this.getRolesList()
                this.roleVisible = false
              } else {
                this.$message.error(message)
              }
            })
        } else { // 验证失败
          for (var key in error) {
            if (error[key]) {
              const message = error[key][0].message
              this.$message.error(message)
              return
            }
          }
        }
      })
    },
    // 关闭弹框
    closeModal() {
      this.roleVisible = false
      this.form = this.$options.data().form
      this.changeSelect(false)
      this.changeExpanded(false)
    },
    // 删除角色
    deleteRole(id) {
      this.$confirm('确认删除', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'none'
      }).then(() => {
        removeRoleAPi(id)
          .then(res => {
            const { message, success } = res
            if (success) {
              this.$message.success('删除角色成功')
              this.getRolesList()
            } else {
              this.$message.error(message)
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 改变limit一页多少条数据
    handleSizeChange(e) {
      this.pagination.limit = e
      this.pagination.start = 1
      this.getRolesList()
    },
    // 改变当前页数start
    handleCurrentChange(e) {
      this.pagination.start = e
      this.getRolesList()
    },
    // 获取全部角色列表通过页码
    getRolesList() {
      findRolesByPageApi(this.pagination.start, this.pagination.limit)
        .then(res => {
          const { message, success, data } = res
          if (success) {
            this.roleList = data.rows
            this.pagination.total = data.total
          } else {
            this.$message.error(message)
          }
        })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep label{
  font-weight: 700;
}
.checkbox{
  font-weight: normal;
}
</style>
